<?php

/**
 * Name: 当班班长记录仓储层
 * User: Silent
 * Date: 2025-11-07
 * Time: 15:30:00
 */

namespace App\Repositories\Checkin;

use App\Models\Checkin\DutyLeader;
use App\Repositories\BaseRepository;
use Carbon\Carbon;

class DutyLeaderRepository extends BaseRepository
{
    protected $dutyLeaderLogRepository;

    public function __construct(
        DutyLeader $model,
        DutyLeaderLogRepository $dutyLeaderLogRepository
    ) {
        parent::__construct($model);
        $this->dutyLeaderLogRepository = $dutyLeaderLogRepository;
    }

    /**
     * 创建或更新记录
     */
    public function updateOrCreate(array $attributes, array $values = [])
    {
        return $this->model->updateOrCreate($attributes, $values);
    }

    /**
     * 获取指定日期的当班班长
     */
    public function getDutyLeadersByDate($date)
    {
        return $this->query()
            ->where('duty_date', $date)
            ->with('leader')
            ->get();
    }

    /**
     * 获取指定日期指定班组的当班班长
     */
    public function getTeamDutyLeader($teamName, $date)
    {
        return $this->query()
            ->where('team_name', $teamName)
            ->where('duty_date', $date)
            ->with('leader')
            ->first();
    }

    /**
     * 根据员工ID和日期获取值班班长记录
     */
    public function getDutyLeaderByEmployeeAndDate($employeeId, $date)
    {
        return $this->query()
            ->where('leader_id', $employeeId)
            ->where('duty_date', $date)
            ->with('leader')
            ->first();
    }

    /**
     * 设置当班班长
     */
    public function setDutyLeader($leaderData, $teamName, $date = null)
    {
        $date = $date ?: today();

        $data = [
            'duty_date' => $date,
            'leader_id' => $leaderData['id'],
            'leader_name' => $leaderData['name'],
            'team_name' => $teamName,
            'is_notified' => false,
            'notified_at' => null,
        ];

        $dutyLeader = $this->updateOrCreate([
            'duty_date' => $date,
            'team_name' => $teamName,
        ], $data);

        // // 记录值班班长日志
        // $this->dutyLeaderLogRepository->createLog(
        //     $dutyLeader->id,
        //     $leaderData['id'],
        //     $teamName,
        //     $date
        // );

        return $dutyLeader;
    }

    /**
     * 批量设置当班班长
     */
    public function batchSetDutyLeaders($dutyData, $date = null)
    {
        $date = $date ?: today();
        $results = [];

        foreach ($dutyData as $item) {
            $results[] = $this->setDutyLeader(
                $item['leader'],
                $item['team_name'],
                $date
            );
        }

        return $results;
    }

    /**
     * 获取当天的当班班长
     */
    public function getTodayDutyLeaders()
    {
        return $this->getDutyLeadersByDate(today());
    }

    /**
     * 获取未通知的当班班长
     */
    public function getUnnotifiedDutyLeaders($date = null)
    {
        $date = $date ?: today();

        return $this->query()
            ->where('duty_date', $date)
            ->where('is_notified', false)
            ->with('leader')
            ->get();
    }

    /**
     * 标记为已通知
     */
    public function markAsNotified($id)
    {
        return $this->update($id, [
            'is_notified' => true,
            'notified_at' => now()
        ]);
    }

    /**
     * 获取当班班长列表（分页）
     */
    public function getDutyLeadersList($perPage = 15, $filters = [])
    {
        $query = $this->query();

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('duty_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('duty_date', '<=', $filters['end_date']);
        }

        // 班组筛选
        if (isset($filters['team_name'])) {
            $query->where('team_name', $filters['team_name']);
        }

        // 班长筛选
        if (isset($filters['leader_id'])) {
            $query->where('leader_id', $filters['leader_id']);
        }

        return $query->with('leader')
                    ->orderBy('duty_date', 'desc')
                    ->orderBy('team_name')
                    ->paginate($perPage);
    }

    /**
     * 获取某个班长的当班记录
     */
    public function getLeaderDutyRecords($leaderId, $perPage = 15, $filters = [])
    {
        $query = $this->query()->where('leader_id', $leaderId);

        // 日期筛选
        if (isset($filters['start_date'])) {
            $query->where('duty_date', '>=', $filters['start_date']);
        }
        if (isset($filters['end_date'])) {
            $query->where('duty_date', '<=', $filters['end_date']);
        }

        return $query->orderBy('duty_date', 'desc')
                    ->paginate($perPage);
    }

    /**
     * 自动生成下一个工作日的当班班长
     */
    public function autoGenerateNextWorkday()
    {
        $nextWorkday = $this->getNextWorkday();

        // 获取今天的当班班长配置
        $todayDutyLeaders = $this->getTodayDutyLeaders();

        $results = [];
        foreach ($todayDutyLeaders as $dutyLeader) {
            $results[] = $this->setDutyLeader(
                $dutyLeader->leader->toArray(),
                $dutyLeader->team_name,
                $nextWorkday
            );
        }

        return $results;
    }

    /**
     * 获取下一个工作日
     */
    private function getNextWorkday()
    {
        $tomorrow = Carbon::tomorrow();

        // // 如果明天是周六或周日，则跳到下周一
        // if ($tomorrow->isWeekend()) {
        //     return $tomorrow->next(Carbon::MONDAY);
        // }

        return $tomorrow;
    }
}

